
<template>
	<div class="page">
    <a-alert v-if="serverErr" message="请检查服务器配置" type="warning" show-icon closable style="z-index:1"/>
		<div class="logo">
			Torrent Manager
		</div>
    <a-button class="setting-btn" type="default" icon="setting" @click="settingOpen"/>
		<div class="back-wrap"></div>
		<div class="dcenter">
			<a-input-password size="large" v-model="passkey" type="password" @pressEnter="doAuth">
				<a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
			</a-input-password>
      <p class="forget-btn">
        <a-button type="link" size="small" style="color:#fff;" @click="forgot">忘记密码?</a-button>
      </p>
		</div>
    <a-drawer
      title="设置"
      width="100%"
      placement="right"
      :closable="true"
      :visible="settingShow"
      @close="settingClose"
    >
      <a-form-model layout="vertical" :model="settingForm">
        <a-form-model-item label="服务器地址">
          <!-- <a-input v-model="settingForm.serverUrl" placeholder="填写完整地址，如：http://127.0.0.1:6699" /> -->
          <a-input-group compact>
            <a-select v-model="settingForm.serverProtocol" style="width: 25%">
              <a-select-option value="http">
                http://
              </a-select-option>
              <a-select-option value="https">
                https://
              </a-select-option>
            </a-select>
            <a-input style="width: 75%" v-model="settingForm.serverHost" placeholder="请填写域名或IP地址" />
          </a-input-group>
        </a-form-model-item>
        <a-form-model-item label="端口">
          <a-input type="number" v-model="settingForm.serverPort" />
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" block @click="settingSave">
            保存
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </a-drawer>
	</div>
</template>

<script>
import store from '../store'
import AuthApi from '../api/AuthApi.js'

export default {
  name: 'Login',
  data() {
    return {
      serverErr: false,
      settingShow: false,
      settingForm: {
        serverProtocol: 'http',
        serverHost: '',
        serverPort: '6699'
      },
      passkey: ''
    }
  },
  mounted() {
    const serverConfigLs = localStorage.getItem('serverConfig')
    if (!serverConfigLs) {
      this.serverErr = true
    } else {
      this.settingForm = JSON.parse(serverConfigLs)
    }
    this.netCheck()
  },
  methods: {
    netCheck() {
      this.serverErr = false
      if (!this.settingForm.serverHost) {
        this.serverErr = true
      } else {
        AuthApi.check().then(response => {
          if (response.data.code === 1) {
            this.$router.replace({
              path: '/torrent'
            })
          } else {
            const serverUrl = store.state.serverUrl
            chrome.cookies.get({ name: 'TM-Token', url: serverUrl }, cookie => {
              // console.log(cookie)
              if (cookie && cookie.value) {
                store.dispatch('setToken', cookie.value)
                this.$router.replace({
                  path: '/torrent'
                })
              }
            })
          }
        }).catch(() => {
          this.serverErr = true
        })
      }
    },
    settingOpen() {
      const serverConfigLs = localStorage.getItem('serverConfig')
      if (serverConfigLs) {
        this.settingForm = JSON.parse(serverConfigLs)
      }
      this.settingShow = true
    },
    settingClose() {
      this.settingShow = false
    },
    settingSave() {
      localStorage.setItem('serverConfig', JSON.stringify(this.settingForm))
      const serverUrl = this.settingForm.serverProtocol + '://' + this.settingForm.serverHost + (this.settingForm.serverPort ? ':' + this.settingForm.serverPort : '')
      store.dispatch('setServerUrl', serverUrl)
      // this.$message.success('设置已保存')
      this.settingShow = false
      this.netCheck()
    },
    doAuth() {
      if (this.passkey) {
        AuthApi.doAuth({ passkey: this.passkey }).then(response => {
          if (response.data.code === 1) {
            store.dispatch('setToken', response.data.data)
            this.$router.replace({
              path: '/torrent'
            })
            // 同步web登录状态
            const serverUrl = store.state.serverUrl
            chrome.cookies.set({ name: 'TM-Token', url: serverUrl, value: store.state.token }, () => {
              chrome.tabs.query({ url: serverUrl + '/*', currentWindow: true }, tabs => {
                if (tabs.length > 0) {
                  chrome.tabs.reload(tabs[0].id)
                }
              })
            })
          } else {
            this.$message.error(`认证失败：${response.data.message}`)
          }
        })
      }
    },
    forgot() {
      alert('开发中')
    }
  }
}
</script>
<style scoped>
.page {
  width: 100%;
  height: 100%;
  background-color: #000;
}
.back-wrap {
  width: 100%;
  height: 80%;
  background-color: #f15a2c;
  background: -webkit-gradient(linear,left top,right top,from(#e22828),to(#ff8c2f));
  background: linear-gradient(90deg,#e22828,#ff8c2f);
  transform:skewY(-5deg);
  -ms-transform:skewY(-5deg); /* IE 9 */
  -webkit-transform:skewY(-5deg); /* Safari and Chrome */
  transform-origin: left;
  -ms-transform-origin: left;
  -webkit-transform-origin: left;
}
.logo {
  position: absolute;
  top: 20px;
  left: 20px;
  line-height: 31px;
  color: #fff;
  font-weight: bolder;
  font-size: 30px;
  width: 320px;
  height: 31px;
  z-index: 2;
}
.setting-btn {
  position: absolute;
  bottom: 10px;
  right: 10px;
}
.dcenter {
  width: 300px;
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.forget-btn {
  text-align: right;
}
</style>
